package com.sky.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EditPasswordDTO;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.BaseException;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 员工信息 前端控制器
 * </p>
 *
 * @author wang
 * @since 2023-07-06
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    @GetMapping("/page")
    public Result page(EmployeePageQueryDTO employeePageQueryDTO){
        Page<EmployeeDTO> employeeDTOPage = employeeService.pageEmp(employeePageQueryDTO);
        return Result.success(employeeDTOPage);
    }

    @PostMapping
    public Result saveEmp(@RequestBody Employee employee){
        String idNumber = employee.getIdNumber();
        employee.setPassword(DigestUtils.md5DigestAsHex(idNumber.substring(idNumber.length()-6,idNumber.length()).getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //线程中获取当前用户id
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        boolean save = employeeService.save(employee);
        return Result.success(save ? "添加成功！" : "添加失败，请重试！");
    }

    @GetMapping("{id}")
    public Result getEmpById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        EmployeeDTO employeeDTO = new EmployeeDTO();
        BeanUtils.copyProperties(employee,employeeDTO);
        return Result.success(employeeDTO);
    }

    @PutMapping
    public Result updateEmpById(@RequestBody Employee employee){
        boolean update = employeeService.updateById(employee);
        return Result.success(update ? "修改成功" : "修改失败");
    }

    @PostMapping("/status/{statusId}")
    public Result updateStatus(@PathVariable Long statusId, Long id){
        LambdaUpdateWrapper<Employee> employeeLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        employeeLambdaUpdateWrapper.eq(Employee::getId,id);
        employeeLambdaUpdateWrapper.set(Employee::getStatus,statusId);
        boolean update = employeeService.update(employeeLambdaUpdateWrapper);
        return Result.success(update ? "更新状态成功" : "操作失败，请重试");

    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    @PutMapping("/editPassword")
    public Result editPassword(@RequestBody EditPasswordDTO editPasswordDTO){
        Long empId = BaseContext.getCurrentId();
        Employee employee = employeeService.getById(empId);
        if (employee.getStatus() == 0){
            throw new BaseException("员工状态锁定，无法修改");
        }
        String oldPassword = editPasswordDTO.getOldPassword();
        oldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (employee.getPassword().equals(oldPassword)){
            String newPassword = DigestUtils.md5DigestAsHex(editPasswordDTO.getNewPassword().getBytes());
            employee.setPassword(newPassword);
            employeeService.updateById(employee);
            return Result.success("修改成功");
        }
        return Result.error("密码错误");
    }
}
